//
//  FYFirstListAction.m
//  ThePainter
//
//  Created by Sean on 15/8/13.
//  Copyright (c) 2015年 FeiYu. All rights reserved.
//

#import "FYFirstListViewModel.h"
#import "FYFirstListModel.h"
#import "FYCache.h"
#import "FYStorage.h"


static int pageNum = 0;
static NSString *FirstListPageData = @"FirstListPageData";

@implementation FYFirstListViewModel

- (void)loadNewData:(id)key valueBlock:(ReturnValueBlock)valueBlock errorBlock:(ErrorCodeBlock)errorBlock failureBlock:(FailureBlock)failureBlock {
    
    //    NSDictionary *parameter = @{};
    //    [self NetRequestPOSTWithRequestURL:FYFirstListPageURL WithParameter:parameter WithReturnValeuBlock:^(id returnValue) {
    //
    //        NSDictionary *dic = returnValue;
    //    } WithErrorCodeBlock:^(id errorCode) {
    //        errorBlock(errorCode);
    //    } WithFailureBlock:^{
    //        failureBlock();
    //    }];
    //-------测试数据----------
    NSString *path = [[NSBundle mainBundle] pathForResource:@"FYFirstListPageData" ofType:@""];
    NSString *productsStr = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    NSArray *arr = [FYUtils arrayWithJsonString:productsStr];
//    NSLog(@"---arr---%@", arr);
    
    //持久化数据
    [FYStorage saveArray:arr withKey:FirstListPageData];
    //缓存list到内存
    [FYCache shareInstance].firstListPageListCache = arr;
    //获取list前十条
    pageNum = 10;
    NSArray *temp = [arr subarrayWithRange:NSMakeRange(0, arr.count > pageNum ? pageNum : arr.count)];
    //转成jsonmodel
    NSArray *products = [FYFirstListModel objectArrayWithKeyValuesArray:temp];
    //刷新列表
    valueBlock(products);
   
}

- (void)loadMoreData:(id)key valueBlock:(ReturnValueBlock)valueBlock errorBlock:(ErrorCodeBlock)errorBlock failureBlock:(FailureBlock)failureBlock {
    //如果是最后一个，不再获取数据
    if (pageNum == -1) {
        failureBlock();
        return;
    }
    //页数增加
    pageNum += 10;
    //从cache获取数据
    NSArray *arr = [FYCache shareInstance].firstListPageListCache;
    //获取前pageNum条
    NSArray *temp = [arr subarrayWithRange:NSMakeRange(0, pageNum < arr.count ? pageNum : (int)arr.count)];
    //转成jsonmodel
    NSArray *products = [FYFirstListModel objectArrayWithKeyValuesArray:temp];
    //刷新列表
    valueBlock(products);
    //如果已经是最后一个，设置pageNum的标志位-1
    pageNum = pageNum < arr.count ? pageNum : -1;
}

@end
